#include "../head/configform.h"
#include "ui_configform.h"
#include <QMessageBox>
#include <QSerialPortInfo>
#include <QDateTime>
#include <QDebug>
#include "../head/utils/MutiSerialControl.h"

#include <QThread>
#include <QHostAddress>
#include <QFile>
#include "../head/utils/tcpclient.h"
extern TcpClient client_;

extern MutiSerialControl *mutiSerialControl;

enum eSignalID{E_SERIEL=0,E_NETWORK};


ConfigForm::ConfigForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConfigForm)
{
    ui->setupUi(this);
    this->setWindowTitle("串口设置");

     setWindowFlags(Qt::WindowCloseButtonHint|Qt::CustomizeWindowHint);
    //获取串口信息
    QStringList serialNamePort;
    foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
       serialNamePort<<info.portName();
    }
    ui->serial_2->addItems(serialNamePort);
   // ui->serial_3->addItems(serialNamePort);
    ui->serial_8->addItems(serialNamePort);


    heartbeat_timer_ = new QTimer(this);
    QObject::connect(this, &ConfigForm::connectHost, &client_, &TcpClient::onConnectHost);
    QObject::connect(&client_, &TcpClient::recvData, this, &ConfigForm::on_recvData);
    QObject::connect(&client_, &TcpClient::clientError, this, &ConfigForm::on_clientError);
    QObject::connect(&client_, &TcpClient::connected, this, &ConfigForm::on_connected);
    initComPort();
}


void ConfigForm::on_recvData(const QString & str){

}

void ConfigForm::on_clientError(const QString & erro){

}


void ConfigForm::on_connected(const int port)
{
    //启动心跳检测
    heartbeat_timer_->start(3000);
    QMessageBox::information(this, "anTcpClient", "Server Connected!");
}


ConfigForm::~ConfigForm()
{
    delete ui;

}

//关闭窗口回到导航界面
 void ConfigForm::closeEvent(QCloseEvent *e)
 {
 }


 /**
 *  \brief  连接低频串口
 *
 *
 **/
void ConfigForm::on_connectButton_clicked()
{
    int portNum = 0;
    mutiSerialControl->portStatus[3] = 0;
    QSerialPort::BaudRate baudRate = (QSerialPort::BaudRate)ui->baundrate_2->currentText().toInt();
    QSerialPort::DataBits dataBits = (QSerialPort::DataBits)ui->data_2->currentText().toInt();
    QSerialPort::StopBits stopBits = (QSerialPort::StopBits)ui->stop_2->currentText().toInt();
    QSerialPort::Parity checkBits;
    if(ui->check_2->currentText() == "none")
    {
        checkBits = QSerialPort::NoParity;
    }else if(ui->check_2->currentText() == "奇校验")
    {
        checkBits = QSerialPort::OddParity;

    }else if(ui->check_2->currentText() == "偶校验")
    {
        checkBits = QSerialPort::EvenParity;
    }


    if(mutiSerialControl->serialPort[portNum]->isOpen()){
        QMessageBox::information(this,"提示","串口断开成功");
        mutiSerialControl->serialPort[portNum]->close();
        mutiSerialControl->stop_Serial(portNum);
        ui->connectButton->setText("连接");
        emit sendStatusMessage("断开",portNum);
    }else{
        mutiSerialControl->serialPort[portNum]->setPortName(ui->serial_2->currentText());
        mutiSerialControl->serialPort[portNum]->setBaudRate(baudRate);
        mutiSerialControl->serialPort[portNum]->setDataBits(dataBits);
        mutiSerialControl->serialPort[portNum]->setStopBits(stopBits);
        mutiSerialControl->serialPort[portNum]->setParity(checkBits);

        if(mutiSerialControl->serialPort[portNum]->open(QIODevice::ReadOnly) == true){
            mutiSerialControl->start_Serial(portNum);
            QMessageBox::information(this,"提示","串口连接成功");
            ui->connectButton->setText("断开");
            writeComPort(ui->serial_2->currentText(),"","");
            emit sendStatusMessage(ui->serial_2->currentText()+"已连接",portNum);
        }else{
            QMessageBox::critical(this,"提示","串口连接失败");
            emit sendStatusMessage(ui->serial_2->currentText()+"连接失败",portNum);
        }
    }
}





void ConfigForm::initComPort(){
    QString fileName = QApplication::applicationDirPath() + "/conf/conf_comport.txt";
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly)){
        qDebug()<<"打开失败";
    }

    QTextStream in(&file);
    QStringList  user_data;
    QString acceptPort,sendPort,TCPIPInfo;
    int i = 0;

    while(!in.atEnd()){
        i++;
        QString line = in.readLine();
        user_data = line.split("=");
        if(i == 1){
            acceptPort = user_data[1];
        }else if(i == 2){
            sendPort  = user_data[1];
        }else if(i == 3){
            TCPIPInfo  = user_data[1];
        }
    }
    file.close();
    if(acceptPort.length() > 0){
         int index = ui->serial_2->findText(acceptPort);

         if(index != -1){
             ui->serial_2->setCurrentIndex(index);
         }
    }

    if(sendPort.length() > 0){
         int index = ui->serial_8->findText(sendPort);

         if(index != -1){
             ui->serial_8->setCurrentIndex(index);
         }
    }

    if(TCPIPInfo.length() > 0){
        QStringList  tcp_port = TCPIPInfo.split(":");
        ui->lineIP->setText(tcp_port[0]);

        ui->linePort->setText(tcp_port[1]);
    }

}

void ConfigForm::writeComPort(QString acc,QString sen,QString TcpIp){
    QString fileName = QApplication::applicationDirPath() + "/conf/conf_comport.txt";
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly)){
        qDebug()<<"打开失败";
    }

    QTextStream in(&file);
    QStringList  user_data;
    QString acceptPort,sendPort,TCPIPInfo;
    int i = 0;

    while(!in.atEnd()){
        i++;
        QString line = in.readLine();
        user_data = line.split("=");
        if(i == 1){
            acceptPort = user_data[1];
        }else if(i == 2){
            sendPort  = user_data[1];
        }else if(i == 3){
            TCPIPInfo  = user_data[1];
        }
    }
   file.close();

    if(acc.length() > 1){
        acceptPort = acc;
    }
    if(sen.length() > 1){
        sendPort = sen;
    }
    if(TcpIp.length() > 1){
        TCPIPInfo = TcpIp;
    }




    QFile file1(fileName);
    file1.open(QIODevice::WriteOnly);
    QString acceptStr = "acceptPort="+acceptPort+"\n";

    file1.write(acceptStr.toStdString().data(),acceptStr.length());
    QString sendStr = "sendPort="+sendPort+"\n";

    file1.write(sendStr.toStdString().data(),sendStr.length());

    QString TCPIPStr = "TCPIP=";
    TCPIPStr.append(TCPIPInfo);

    file1.write(TCPIPStr.toStdString().data(),TCPIPStr.length());

    file1.close();

}

/**
*  \brief  连接发送串口
*
*
**/
void ConfigForm::on_connectButton_2_clicked()
{
    QSerialPort::BaudRate baudRate = (QSerialPort::BaudRate)ui->baundrate_8->currentText().toInt();
    QSerialPort::DataBits dataBits = (QSerialPort::DataBits)ui->data_8->currentText().toInt();
    QSerialPort::StopBits stopBits = (QSerialPort::StopBits)ui->stop_8->currentText().toInt();
    QSerialPort::Parity checkBits;
    if(ui->check_8->currentText() == "none")
    {
        checkBits = QSerialPort::NoParity;
    }else if(ui->check_8->currentText() == "奇校验")
    {
        checkBits = QSerialPort::OddParity;

    }else if(ui->check_8->currentText() == "偶校验")
    {
        checkBits = QSerialPort::EvenParity;
    }

    qDebug()<<"ui->serial_2->currentText()"<<ui->serial_2->currentText()<<":baudRate="<<baudRate<<endl;

    if(mutiSerialControl->sendDecDataPort->isOpen()){
        QMessageBox::information(this,"提示","串口断开成功");
        mutiSerialControl->sendDecDataPort->close();
        mutiSerialControl->stop_Serial(1);
        ui->connectButton_2->setText("连接");
        mutiSerialControl->portStatus[1] = 0;
        emit sendStatusMessage("断开",1);
    }else{
        mutiSerialControl->sendDecDataPort->setPortName(ui->serial_8->currentText());
        mutiSerialControl->sendDecDataPort->setBaudRate(baudRate);
        mutiSerialControl->sendDecDataPort->setDataBits(dataBits);
        mutiSerialControl->sendDecDataPort->setStopBits(stopBits);
        mutiSerialControl->sendDecDataPort->setParity(checkBits);

        if(mutiSerialControl->sendDecDataPort->open(QIODevice::ReadWrite) == true){
            mutiSerialControl->portStatus[1] = 1;
            QMessageBox::information(this,"提示","串口连接成功");
            ui->connectButton_2->setText("断开");
            writeComPort("",ui->serial_8->currentText(),"");
            emit sendStatusMessage(ui->serial_8->currentText()+"已连接",1);
        }else{
            QMessageBox::critical(this,"提示","串口连接失败");
            //emit sendStatusMessage(ui->serial_8->currentText()+"连接失败");
        }
    }

}


void ConfigForm::on_connectButton_4_clicked()
{
    if (ui->lineIP->text().isEmpty()){
        QMessageBox::information(this, "anTcpClient", "please input ip addr!");
        return;
    }
    if (ui->linePort->text().isEmpty()){
        QMessageBox::information(this, "anTcpClient", "please input port!");
        return;
    }

    emit connectHost(ui->lineIP->text(), ui->linePort->text().toInt());

    QString tempTcpIp;
    tempTcpIp.append(ui->lineIP->text());
    tempTcpIp.append(":");
    tempTcpIp.append(ui->linePort->text());

    writeComPort("","",tempTcpIp);
}
